package com.hll.spring_book.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hll.spring_book.pojo.Book;
import com.hll.spring_book.pojo.Borrow;
import com.hll.spring_book.service.book.BookService;
import com.hll.spring_book.service.borrow.BorrowService;
import com.hll.spring_book.util.CommonResult;
import com.hll.spring_book.util.Constants;
import com.hll.spring_book.util.SessionHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

/**
 * @author: Mr.Hu
 * @create: 2021-03-30 16:53
 */
@RequestMapping("/borrow")
@RestController
public class BorrowController {
  @Resource private BorrowService borrowService;
  @Resource private BookService bookService;

  @PostMapping("add")
  /*借书*/
  public CommonResult borrowBook(
      @RequestParam("bookId") Integer bookId, HttpServletRequest request) {
    // 用户id从session中取，所以登录才行，不可能代借书
    Integer userId = SessionHelper.getUser().getId();
    // 如果用户存在该书未还
    if (borrowService.hasBorrowedBook(userId, bookId))
      return new CommonResult(Constants.FAIL, "你已经借了相同的书并且未归还", null);
    // 书的库存
    if (bookService.queryById(bookId).getCount() <= 0)
      return new CommonResult(Constants.FAIL, "此书暂无供应", null);
    if (userId != null) {
      Book book = bookService.queryById(bookId);
      book.setCount(book.getCount() - 1); // 更新书的库存
      if (bookService.update(book) != null) {
        Borrow insert =
            borrowService.insert(
                new Borrow(null, userId, bookId, Calendar.getInstance().getTime(), null, false));
        if (insert != null) return new CommonResult(Constants.SUCCESS, "借书成功", null);
      }
    }
    return new CommonResult(Constants.FAIL, "借书失败", null);
  }

  // 还书，只需要知道借阅id，其实的话如果是面向用户而非管理员使用的话，应该验证该记录的userId和sessionId是否相同
  @PostMapping("return")
  public CommonResult returnBook(@RequestParam("id") Integer id) {
    Borrow borrow = borrowService.queryById(id);
    if (borrow != null) {
      if (borrow.getStatus()) { // 如果已还
        return new CommonResult(Constants.FAIL, "该书已还,请勿重复操作", null);
      }
      Book book = bookService.queryById(borrow.getBookId());
      if (book != null) {
        /*说明书籍不存在*/
        book.setCount(book.getCount() + 1); // 书加一
        if (bookService.update(book) != null) {
          borrow.setReturnTime(Calendar.getInstance().getTime());
          borrow.setStatus(true);
          if (borrowService.update(borrow) != null)
            return new CommonResult(Constants.SUCCESS, "还书成功", null);
        }
      }
    }
    return new CommonResult(Constants.FAIL, "还书失败亦或者借阅记录不存在", null);
  }

  // 查询个人的借阅记录，userId从session中取
  @PostMapping("queryPersonalBorrowsInfo")
  public PageInfo<Borrow> queryPersonalBorrowsInfo(
      @RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo,
      @RequestParam(defaultValue = "5", value = "pageSize") Integer pageSize,
      @RequestParam(value = "status", required = false) Boolean status) {
    Integer userId = SessionHelper.getUser().getId();
    if (userId == null) return null;
    return this.queryALlBorrowInfoByLimit(pageNo, pageSize, userId, status);
  }

  // 查询所有记录，面向管理员
  @PostMapping("queryBorrowsInfo")
  public PageInfo<Borrow> queryALlBorrowInfoByLimit(
      @RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo,
      @RequestParam(defaultValue = "5", value = "pageSize") Integer pageSize,
      @RequestParam(value = "id", required = false) Integer userId,
      @RequestParam(value = "status", required = false) Boolean status) {
    PageHelper.startPage(pageNo, pageSize);
    Borrow borrow = new Borrow();
    borrow.setStatus(status);
    borrow.setUserId(userId);
    return new PageInfo<>(borrowService.queryAllByLimit(borrow));
  }

  @PostMapping("queryAllBorrows")
  public List<Borrow> queryALlBorrowInfo(
      @RequestParam(value = "id", required = false) Integer userId,
      @RequestParam(value = "status", required = false) Boolean status) {
    Borrow borrow = new Borrow();
    borrow.setStatus(status);
    borrow.setUserId(userId);
    return borrowService.queryAllByLimit(borrow);
  }

  /*删除记录，理应分为用户和管理员*/
  @PostMapping("delete")
  public CommonResult deleteInfo(@RequestParam("id") Integer id) {
    /*如果书籍被删了，可直接删除*/
    Borrow borrow = borrowService.queryById(id);
    Book book = bookService.queryById(borrow.getBookId());
    if (!borrow.getStatus() && book != null)
      return new CommonResult(Constants.FAIL, "书未归还，无法删除记录", null);
    if (borrowService.deleteById(id)) return new CommonResult(Constants.SUCCESS, "删除成功", null);
    return new CommonResult(Constants.FAIL, "删除失败", null);
  }
}
